package com.stroke.util;

import com.stroke.tools.animation.Frame;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
 * Author: Igor Bubelov
 * Date: 3/8/11 10:02 PM
 */
public class AnimationHelper {
    public static void saveAnimation(File file, List<Frame> frames) {
        if (file.exists()) {
            Logger.getLogger(AnimationHelper.class).debug("File " + file.getName() + " already exists. Overriding...");
            file.delete();
        }

        StringBuilder descriptionBuilder = new StringBuilder();
        descriptionBuilder.append("<animation>\n");

        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));

            int i = 1;
            for (Frame frame : frames) {
                String fileName = String.format("%s.%s", frame.getPosition(), frame.getFormat());

                File frameFile = new File("~" + fileName);
                ImageIO.write((RenderedImage) frame.getImage(), frame.getFormat(), frameFile);

                FileInputStream in = new FileInputStream(frameFile);

                IOHelper.addZipEntry(out, in, fileName);

                frameFile.delete();

                descriptionBuilder.append(frameDescription(i, fileName));

                i++;
            }

            descriptionBuilder.append("</animation>");

            ByteArrayInputStream descriptionStream = new ByteArrayInputStream(descriptionBuilder.toString().getBytes());

            IOHelper.addZipEntry(out, descriptionStream, "description.xml");

            out.close();
        } catch (Exception ex) {
            Logger.getLogger(AnimationHelper.class).error("Failed to create an animation file", ex);
        }
    }

    private static String frameDescription(int n, String fileName) {
        return String.format("\t<frame number=\"%s\" file=\"%s\"/>\n", n, fileName);
    }
}